{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 重排数组，让奇数位于偶数前面"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "vscode": {
     "languageId": "cpp"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "partition: 7 1 3 5 2 6 4 \n",
      "stable_partition: 1 3 5 7 4 2 6 \n"
     ]
    }
   ],
   "source": [
    "#include <algorithm>  // std::partition, std::stable_partition\n",
    "#include <iostream>   // std::cout\n",
    "#include <vector>     // std::vector\n",
    "\n",
    "{\n",
    "    // 原始数据：混合奇偶数\n",
    "    std::vector<int> data{4, 1, 3, 2, 5, 6, 7};\n",
    "\n",
    "    // 方式一：std::partition（不稳定，时间复杂度 O(n)，空间复杂度 O(1)）\n",
    "    //\n",
    "    // 作用：根据谓词（lambda）将容器划分为两部分；\n",
    "    //       前半部分满足谓词（返回 true），后半部分不满足。\n",
    "    // By design，它不会保留满足条件元素之间的相对顺序。\n",
    "    std::vector<int> partitioned = data;  // 复制一份原始数据\n",
    "    std::partition(partitioned.begin(), partitioned.end(),\n",
    "                   [](int x) { return x % 2 != 0; }); // 奇数返回 true，移动到前面\n",
    "\n",
    "    std::cout << \"partition: \";\n",
    "    for (int v : partitioned) {\n",
    "        std::cout << v << ' ';\n",
    "    }\n",
    "    std::cout << '\\n';\n",
    "\n",
    "    // 方式二：std::stable_partition（稳定，保留奇数之间及偶数之间的原始相对顺序）\n",
    "    //\n",
    "    // 代价：通常需要额外的辅助空间来维持稳定性；部分实现可能是 O(n log n)。\n",
    "    std::vector<int> stable = data;\n",
    "    std::stable_partition(stable.begin(), stable.end(),\n",
    "                          [](int x) { return x % 2 != 0; });\n",
    "\n",
    "    std::cout << \"stable_partition: \";\n",
    "    for (int v : stable) {\n",
    "        std::cout << v << ' ';\n",
    "    }\n",
    "    std::cout << '\\n';\n",
    "}"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "C++17",
   "language": "C++17",
   "name": "xcpp17"
  },
  "language_info": {
   "codemirror_mode": "text/x-c++src",
   "file_extension": ".cpp",
   "mimetype": "text/x-c++src",
   "name": "C++17",
   "version": "17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
